const nodeExcel = require('excel-export');
const path = require('path');
const fs = require('fs');

const pageQuery = require('../utils/pageQuery')
const AsyncMysqljs = require('../mysql/index')
const Query = AsyncMysqljs().query


module.exports = async (ctx, next) => {
    const {page, pageSize, value} = ctx.request.query
    let outFilename = "export.xml";
    let address = path.join(__dirname,outFilename);
    fs.exists(address ,function(exist){
        if(exist){
            console.log("file exist!");
        }else{
            try{
                fs.open(address,'w+',function(err,fd){
                    console.log('try to create file!');
                });
            }catch(err){
                console.log('file not exist');
            }
        }
    });

    var conf ={};
    conf.stylesXmlFile = outFilename;//输出文件名
    conf.name = "mysheet";//表格名
    //定义表格列字段
    conf.cols = [
        {
            caption:'id',
            type:'number',
            width:28.7109375
        },
        {
            caption:'date',
            type:'string'
        },
        {
            caption:'time',
            type:'string'
        },
        {
            caption:'uid',
            type:'number'
        },
        {
            caption:'mobile',
            type:'string',
            width:80
        },
        {
            caption:'name',
            type:'string'
        },
        {
            caption:'roleName',
            type:'string'
        },
        {
            caption:'vid',
            type:'number'
        },
        {
            caption:'vendorName',
            type:'string'
        },
        {
            caption:'systemType',
            type:'number'
        },
        {
            caption:'eventTag',
            type:'string',
            width:80
        },
        {
            caption:'desc',
            type:'string',
            width:120
        },
        {
            caption:'ip',
            type:'string'
        }
    ];
    //填充表格数据
    conf.rows = [
        [9,'2016-06-20','16:22:31',1504,'13000000006','呵呵','店长',56,'美容护肤',2,'订单管理','获取订单详情','127.0.0.1'],
        [8,'2016-06-20','16:22:31',1504,'13000000006','呵呵','店长',56,'美容护肤',2,'订单管理','获取订单列表','192.168.145.162'],
    ];

    //生成excel文件
    var result = nodeExcel.execute(conf);
    console.log("原始数据：",result);
    //方法一：写入二进制到文件，读出二进制
    // fs.writeFile(path.join(__dirname,'log.xlsx'),result,{encoding:'binary'},function (err) {
        // if(err){console.log('写入错误');}
    // })
    //
    // let data = yield  readData(path.join(__dirname,'log.xlsx'));

    //将数据转为二进制输出
    let data = new Buffer(result,'binary');
    this.set('Content-Type', 'application/vnd.openxmlformats');
    this.set("Content-Disposition", "attachment; filename=" + "export.xlsx");
    console.log("处理数据：",data);
    ctx.body = data;
};
